package com.frame.work.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import java.util.UUID;

/**
 * 分布式链路
 *
 * @author wjming
 */
public class DistributedLink {
    private static final String FLAG = "EagleEye-TraceID";

    /**
     * 生成分布式链路ID
     *
     * @return
     */
    public static void createId() {
        MDC.clear();
        String traceId = MDC.get(FLAG);
        if (StringUtils.isEmpty(traceId)) {
            traceId = UUID.randomUUID().toString();
        }
        MDC.put(FLAG, traceId);
    }

    /**
     * 获取分布式链路ID
     *
     * @return
     */
    public static String getId() {
        String traceId = MDC.get(FLAG);
        if (StringUtils.isEmpty(traceId)) {
            traceId = UUID.randomUUID().toString();
        }
        return traceId;
    }

    public static void putTraceId(String traceId) {
        MDC.clear();
        if (StringUtils.isEmpty(traceId)) {
            traceId = UUID.randomUUID().toString();
        }
        MDC.put(FLAG, traceId);
    }
}
